<template>
  <div class="login-container">
    <div>
      <img class="logo" src="@/assets/login/logo.png" />
    </div>
    <div class="login_bg">
      <div class="login">
        <h2 class="title">华西绿舍 · ICPS</h2>
        <el-form ref="loginForm" size="small" :model="loginForm" :rules="loginRules" autocomplete="off" label-position="left">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入账号" name="username" type="text" tabindex="1" autocomplete="off" @keyup.enter.native="handleLogin">
              <i slot="prefix" :style="istyle" class="el-icon-user-solid"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码" name="password" type="password" tabindex="2" autocomplete="off" @keyup.enter.native="handleLogin">
              <i slot="prefix" :style="istyle" class="el-icon-s-goods"></i>
            </el-input>
          </el-form-item>
          <!-- <el-form-item>
            <el-checkbox size="mini" v-model="loginForm.checked">记住密码</el-checkbox>
          </el-form-item>-->
        </el-form>
        <div class="input">
          <el-button type="primary" :loading="loading" round @click="handleLogin()">登录</el-button>
        </div>

        <h4>其他登录方式</h4>
        <div class="other-login">
          <el-tooltip class="item" effect="dark" content="微信" placement="top">
            <img src="@/assets/login/WeChat.png" alt="微信" @click="login('wechat')">
          </el-tooltip>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getPermission } from '@/api/api';
import { getSystemDetails } from '@/api/common';
import { setPerMission } from "@/utils/auth";
import { GetQueryString } from "@/utils/utils"

export default {
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位数"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "123456"
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      loading: false,
      otherQuery: {},
      redirect: undefined,
      isAndroid: false,
      isiOS: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
      beforeUrl: '',
    }
  },
  computed: {
    istyle() {
      return "font-size: 20px;padding: 14px 10px 0 10px;";
    }
  },
  mounted() {
    const u = navigator.userAgent;
    this.isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    this.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    let params = GetQueryString()
    console.log(params)
    if (params.state && params.state === 'login') {
      // 微信登录，查找token
      let code = params.code
      console.log(code)
      if (code) {
        this.$store
          .dispatch("user/wxlogin", {type: 1, code: code})
          .then((res) => {
              if(res && res.code === 1001) {
                  this.getAuth()
              } else {
                  this.loading = false;
              }
          })
          .catch(() => {
            this.loading = false;
          });
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
        vm.beforeUrl = from.path
    })
  },
  /**  销毁enter事件*/
  methods: {
    login(type) {
      let redirect_uri = encodeURIComponent('https://lvshe.huashijc.com/#/login'),
        url = 'https://open.weixin.qq.com/connect/qrconnect?appid=wx71e02854861febfc&redirect_uri=' + redirect_uri +'&response_type=code&scope=snsapi_login&state=login#wechat_redirect'
      switch(type) {
        case 'wechat':
          window.open(url)
        break;
        default: 
        break;
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((res) => {
                if(res && res.code === 1001) {
                    this.getAuth()
                } else {
                    this.loading = false;
                }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    /**
     * 获取用户权限
     * by rogerwei 220109
     */
    getAuth() {
      getPermission().then(res => {
          if (res && res.code === 1001) {
            setPerMission(res.data)
            getSystemDetails({code: 'watermark'}).then(ress => {
                if (ress.code === 1001) {
                  window.sessionStorage.setItem('watermark', ress.data.paramValue);

                  this.$router.push({
                      path: document.referrer || this.beforeUrl === '/' ? "/lvshe/index" : this.beforeUrl || "/lvshe/index",
                      query: {
                      token: window.localStorage.getItem('access-token'),
                      ...this.otherQuery
                      }
                  });
                }
            })
          }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  }
};
</script>
<style lang="scss">
.login-container {
  .el-input__inner {
    border-radius: 24px;
    line-height: 48px !important;
    height: 48px !important;
  }
  .el-input--prefix .el-input__inner {
    padding-left: 46px;
  }
  .el-button {
    height: 48px !important;
    width: 100%;
    background: #028037;
  }
}
</style>
<style lang="scss" scoped>
.login_bg {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: calc(100vh - 141px);
  padding: 0 132px;
  .login {
    width: 456px;
    height: 540px;
    background: #ffffff;
    padding: 57px;
    .title {
      text-align: center;
    }
    .forget {
      line-height: 19px;
      font-size: 14px;
      color: #999999;
    }
    .input {
      display: flex;
      justify-content: space-between;
      padding-top: 24px;
      input {
        height: 48px;
      }
    }

    .other-login {
      img {
        width: 40px;
        cursor: pointer;
      }
    }
  }
}
</style>
